Kill a Process in C# with Example
Sometimes we want to terminate or kill a process, which is already running or previously created process. To kill the process in c sharp use System. Diagnostics namespaces and use named ‘Kill()’ method which is available in Process class.
Here I am giving an example to kill the process. Let’s see a brief description of it. Example: Here I am creating a process and after 2 seconds killed it.
To kill the previously created process writes the following code.
using System.Diagnostics;
namespace ConsoleProcessTest
{
class Program
{
static voidMain(string[] args)
{
// create the process to launch another exe file
Process myProcess= Process.Start(@"C:\Users\Sachindra\Desktop\Logic.exe");
// take 2 second to kill the process
Thread.Sleep(2000);
// kill the process
myProcess.Kill();
}
}
}
After debug this code your Logic.exe executable file will execute and after 2 seconds it will close.
To kill the already running process:
To kill the already running process writes the following code.
using System.Diagnostics;
namespace AllreadyRunningProcess
{
class Program
{
static voidMain(string[] args)
{
// Store all running process in the system
Process[] runingProcess= Process.GetProcesses();
for (inti=0; i<runingProcess.Length; i++)
{
// compare equivalent process by their name
if(runingProcess[i].ProcessName=="mspaint")
{
// kill running process
runingProcess[i].Kill();
}
}
}
}
}
After debugging the code if the ‘MSPaint’ process is running then it will close.
Read this Article - Editable Grid View System using BootStrap in ASP.Net
Anonymous User
04-Jul-2019Thanks for sharing.
Kenny Tangnde
27-Feb-2012hi Arun, this is nice article.
thanks.